// miniprogram/pages/goodsDetail/goodsDetail.js
import moment from "../../utils/moment.js";
const app = getApp()
Page({
    /**
     * 页面的初始数据
     */
    data: {
        goodsDetail: {
            _id: "123",
            name: "Huawei/华为 P10",
            desc: "Huawei/华为 P10 全网通双卡双待4G智能手机 p10plus 指纹解锁",
            listedTime: "2015-1-1",
            saledNum: "15",
            detail_img: [],
            show_img: [],
            parameter: [{
                    name: "X",
                    num: 10,
                    price: 200
                },
                {
                    name: "M",
                    num: 10,
                    price: 200
                },
                {
                    name: "L",
                    num: 10,
                    price: 200
                }
            ]
        },
        parameterItem: [{
                name: "X",
                num: 10,
                price: 200,
                active: false,
            },
            {
                name: "M",
                num: 10,
                price: 200,
                active: false,
            },
            {
                name: "L",
                num: 10,
                price: 200,
                active: false,
            }
        ],
        price: 500,
        selectIndex: null,
        swiperCurrent: 0,
        hasMoreSelect: false,
        selectSize: "选择：",
        selectSizePrice: 0,
        hideShopPopup: true,
        buyNumber: 0,
        buyNumMin: 1,
        buyNumMax: 100,
        shopNum: 0,
        propertyChildIds: "",
        propertyChildNames: "",
        canSubmit: false, //  选中规格尺寸时候是否允许加入购物车
        shopCarInfo: {},
        shopType: "addShopCar", //购物类型，加入购物车或立即购买，默认为加入购物车
    },
    /**
     * 选择商品规格
     * @param {Object} e
     */
    radioChange: function(e) {
        let index = e.currentTarget.dataset.index;
        var radioItems = this.data.parameterItem;
        for (var i = 0, len = radioItems.length; i < len; ++i) {
            if (i == index) {
                radioItems[i].active = true;
                this.setData({
                    selectIndex: i
                })
            } else {
                radioItems[i].active = false;
            }
        }
        this.setData({
            parameterItem: radioItems,
        });
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        if (options.productId) {
            console.log(options.productId)
            let _id = options.productId;
            const db = wx.cloud.database()
            //获取商品列表
            db.collection('product_list').doc(_id).get({
                success: res => {
                    res.data.listed_date = moment(res.data.listed_date).format("YYYY-MM-DD");
                    this.setData({
                        goodsDetail: res.data,
                        parameterItem: res.data.parameter
                    })
                },
                fail: err => {
                    wx.showToast({
                        icon: 'none',
                        title: '查询记录失败'
                    })
                    console.error('[数据库] [查询记录] 失败：', err)
                }
            })

        }
        this.updateShopNum() //获取购物车默认值
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function() {

    },
    /**
     * 控制参数选择框底部按钮
     */
    toAddShopCar: function() {
        this.setData({
            shopType: "addShopCar"
        })
        this.bindGuiGeTap();
    },
    /**
     * 控制参数选择框底部按钮
     */
    tobuy: function() {
        this.setData({
            shopType: "tobuy"
        });
        this.bindGuiGeTap();
    },
    /**
     * 规格选择弹出框
     */
    bindGuiGeTap: function() {
        this.setData({
            hideShopPopup: false
        })
    },
    /**
     * 规格选择弹出框隐藏
     */
    closePopupTap: function() {
        this.setData({
            hideShopPopup: true,
            selectIndex: null
        })
    },
    numJianTap: function() {
        if (this.data.buyNumber > this.data.buyNumMin) {
            var currentNum = this.data.buyNumber;
            currentNum--;
            this.setData({
                buyNumber: currentNum
            })
        }
    },
    numJiaTap: function() {
        if (this.data.buyNumber < this.data.buyNumMax) {
            var currentNum = this.data.buyNumber;
            currentNum++;
            this.setData({
                buyNumber: currentNum
            })
        }
    },
    /**
     * 加入购物车  并写入本地缓存
     */
    addShopCar: function() {
        if (!this.checkIsEnpty()) {
            return
        }
        //组建购物车
        var shopCarInfo = {
            product_id: this.data.goodsDetail._id,
            name: this.data.goodsDetail.name,
            desc: this.data.goodsDetail.desc,
            parameter: this.data.goodsDetail.parameter[this.data.selectIndex],
            buyNumber: this.data.buyNumber,
            show_img: this.data.goodsDetail.show_img[0],
        }
        if (this.addToShopCar(shopCarInfo)) {
            wx.showModal({
                title: '提示',
                content: '添加成功!',
                showCancel: false,
                success: () => {
                    this.closePopupTap();
                    this.updateShopNum();
                }
            })
        } else {
            wx.showModal({
                title: '提示',
                content: '添加失败，请看控制台报错信息!',
                showCancel: false,
                success: () => {
                    this.closePopupTap();
                }
            })
        }
    },
    buyNow: function() {
        if (!this.checkIsEnpty()) {
            return
        }
        //组建购物车
        var shopCarInfo = {
            product_id: this.data.goodsDetail._id,
            name: this.data.goodsDetail.name,
            desc: this.data.goodsDetail.desc,
            parameter: this.data.goodsDetail.parameter[this.data.selectIndex],
            buyNumber: this.data.buyNumber,
            show_img: this.data.goodsDetail.show_img[0],
        }
        if (this.addToShopCar(shopCarInfo)) {
            //跳转
            wx.reLaunch({
                url: "/pages/shopingCart/index",
            })
        } else {
            wx.showModal({
                title: '提示',
                content: '购买失败，请看控制台报错信息!',
                showCancel: false,
                success: () => {
                    this.closePopupTap();
                }
            })
        }
    },
    /**
     * 加入购物车方法
     */
    addToShopCar(obj) {
        try {
            let value = wx.getStorageSync('shopCarInfo')
            if (value && value.shopList) {
                // Do something with return value
                value.shopList.push(obj)
                wx.setStorageSync('shopCarInfo', value)
            } else {
                wx.setStorageSync('shopCarInfo', {
                    shopList: [obj]
                })
            }
            return true
        } catch (e) {
            console.log(e)
            // Do something when catch error
            return false
        }
    },
    /**
     * 添加购物车时检测是否合法
     */
    checkIsEnpty() {
        if (this.data.selectIndex == null) {
            wx.showModal({
                title: '提示',
                content: '请选择商品规格！',
                showCancel: false
            })
            this.bindGuiGeTap();
            return false;
        }
        if (this.data.buyNumber < 1) {
            wx.showModal({
                title: '提示',
                content: '购买数量不能为0！',
                showCancel: false
            })
            return false;
        }
        return true
    },
    /**
     * 用于更新shopnum
     */
    updateShopNum() {
        let shopCarInfo = wx.getStorageSync('shopCarInfo')
        let num = 0;
        if (shopCarInfo && shopCarInfo.shopList) {
            num = shopCarInfo.shopList.length;
        }
        this.setData({
            shopNum: num
        })
    },
    goShopCar: function() {
        wx.reLaunch({
            url: "/pages/shopingCart/index"
        });
    },
})